package definite.Guide.Book.JFileChooser;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.filechooser.FileFilter;

public class JFileChooserWithPopupWindow {

	public static void main(String[] args) {
		Runnable r = new Runnable() {

			@Override
			public void run() {
				JFrame.setDefaultLookAndFeelDecorated(true);
				JFrame frame = new JFrame("JFileChooser Demo");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

				final JLabel dirLabel = new JLabel(" ");
				dirLabel.setFont(new Font("San-Serif", Font.BOLD | Font.ITALIC,
						14));
				frame.add(dirLabel, BorderLayout.NORTH);

				final JLabel fileLabel = new JLabel(" ");
				fileLabel.setFont(new Font("San-Serif",
						Font.BOLD | Font.ITALIC, 14));
				frame.add(fileLabel, BorderLayout.SOUTH);

				JButton button = new JButton("Click to open JFileChooser");
				button.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						JFileChooser chooser = new JFileChooser(".");
						chooser.setControlButtonsAreShown(true);

						// ***************using file filter***********
						FileFilter gifFilter =
							new CustomFileFilter("Gif File",
									new String[] { "GIF" });
						FileFilter jpgFilter =
							new CustomFileFilter("JPG/JPEG File", new String[] {
								"JPG", "JPEG" });
						chooser.addChoosableFileFilter(jpgFilter);
						chooser.addChoosableFileFilter(gifFilter);
						chooser.setFileFilter(jpgFilter);
						// *************************************************

						// adding Accessory Panel
						chooser.setAccessory(new LabelAccessory(chooser));

						// using FileView
						chooser.setFileView(new JavaFileView());

						int status = chooser.showOpenDialog(null);
						if (status == JFileChooser.APPROVE_OPTION) {
							File file = chooser.getSelectedFile();
							dirLabel.setText(file.getParent());
							fileLabel.setText(file.getName());
						} else if (status == JFileChooser.CANCEL_OPTION) {
							dirLabel.setText(" ");
							fileLabel.setText(" ");
						}
					}
				});
				frame.add(button, BorderLayout.CENTER);
				frame.setLocationRelativeTo(null);
				frame.setSize(400, 200);
				frame.setVisible(true);
			}
		};

		EventQueue.invokeLater(r);
	}

}
